package com.wlc.business.util.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;

/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

    /**
     * @param path   接口地址
     * @param params
     * @param encode
     * @param file
     * @return
     * @author: zhangxin
     * @date:2019年3月4日 上午11:56:03
     */
    public static String postFromHttpClient2(String path, Map<String, String> params, String encode, File file) {
        String result = null;
        HttpResponse response = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = SSLClient.getHttpClient();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName(encode));
            HttpPost httppost = new HttpPost(path);
            builder.addBinaryBody("file", file);
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addTextBody(entry.getKey(), entry.getValue());
                }
            }
            HttpEntity entity = builder.build();// 生成 HTTP POST 实体
            httppost.setEntity(entity);

            response = httpclient.execute(httppost);// 发送post请求
            int code = response.getStatusLine().getStatusCode();
            System.out.println(response.getStatusLine());
            if (code == 200) {
                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, encode);
                    }
                }
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return result;
    }
}
